<?php
namespace App\Controller;

use App\Helper\SeoHelper;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\Utils\ApplicationContext;
use Psr\Http\Message\ResponseInterface;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use App\Service\ArticleService;
use App\Job\CategoryJob;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Utils\Coroutine;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

/**
 * @Controller(prefix="api/data")
 */
class DataController
{
    protected $response;
    protected $queue;
    protected $loggerFactory;
    protected $logger;
    protected $logger_db;
    protected $logger_tasklog;

    /**
     * @Inject
     * @var ValidatorFactoryInterface
     */
    protected $validatorFactory;

    public function __construct(
        HttpResponse $response,
        DriverFactory $driverFactory,
        LoggerFactory $loggerFactory,
        ValidatorFactoryInterface $validatorFactory
    ) {
        $this->response         = $response;
        $this->queue            = $driverFactory->get('default');
        $this->loggerFactory    = $loggerFactory;
        $this->validatorFactory = $validatorFactory;
        $this->logger           = $loggerFactory->get('article', 'article');
        $this->logger_db        = $loggerFactory->get('database', 'database');
        $this->logger_tasklog        = $loggerFactory->get('tasklog', 'tasklog');
    }

    /**
     * 直接写入数据
     * @PostMapping(path="irugby_edit_product")
     */
    public function irugbyEditProduct(RequestInterface $request): ResponseInterface
    {
        $getData = $request->all();
        $product_id = (int)$getData['product_id'];

        $db_conn = Db::connection('irugbystore');

        $product = $db_conn->table('oc_product as p')
            ->leftJoin('oc_product_description as pd', 'p.product_id', '=', 'pd.product_id')
            ->where('p.product_id',$product_id)
            ->first();
        if(!$product){
            return $this->response->json([
                'code' => 400,
                'data' => $product_id.'--商品信息不存在'
            ]);
        }

        $english = $getData['english'] ?? [];
        $french = $getData['french'] ?? [];

        if (empty($english) || empty($french)) {
            return $this->response->json([
                'code' => 400,
                'data' => '商品信息数据为空'
            ]);
        }

        $english = $getData['english'];
        $french = $getData['french'];
        $englishData = [
            'name' => trim($english['product_name']),
            'description' => $english['description'],
            'tag' => trim($english['product_tags']),
            'meta_title' => trim($english['meta_title']),
            'meta_description' => trim($english['meta_description']),
            'meta_keyword' => trim($english['meta_keywords']),
            'seo_h1' => trim($english['seo_h1']),
            'seo_h2' => trim($english['seo_h2']),
            'seo_h3' => trim($english['seo_h3']),
            'image_title' => trim($english['product_name']),
            'image_alt' => trim($english['product_name'])
        ];

        $french_product_name = trim($french['product_name']);
        $seoUrl = SeoHelper::generateSeoUrl($french_product_name);

        $existSeoUrl = $db_conn->table('oc_seo_url')
            ->where('store_id', 0)
            ->where('keyword', $seoUrl)
            ->first();
        if($existSeoUrl){
            $seoUrl = $seoUrl.'-'.$product_id;
        }

        $frenchData = [
            'name' => $french_product_name,
            'description' => $french['description'],
            'tag' => trim($french['product_tags']),
            'meta_title' => trim($french['meta_title']),
            'meta_description' => trim($french['meta_description']),
            'meta_keyword' => trim($french['meta_keywords']),
            'seo_keyword' => $seoUrl,
            'seo_h1' => trim($french['seo_h1']),
            'seo_h2' => trim($french['seo_h2']),
            'seo_h3' => trim($french['seo_h3']),
            'image_title' => trim($french['product_name']),
            'image_alt' => trim($french['product_name'])
        ];

        $backData = [
            'product_id' => $product_id,
            'english' => $englishData,
            'french' => $frenchData,
        ];

        //写入数据
        $db_conn->transaction(function ($db_conn) use ($product_id,$englishData,$frenchData) {

            $db_conn->table('oc_product_description')
                ->where('product_id', $product_id)
                ->where('language_id', 1)
                ->update($englishData);


            $db_conn->table('oc_product_description')
                ->where('product_id', $product_id)
                ->where('language_id', 2)
                ->update($frenchData);

            $db_conn->table('oc_product')
                ->where('product_id', $product_id)
                ->update([
                    'status' => 1,
                    'date_modified' => date('Y-m-d H:i:s'),
                ]);

            $db_conn->table('oc_seo_url')
                ->where('store_id', 0)
                ->where('language_id', 2)
                ->where('query', 'product_id='.$product_id)
                ->update([
                    'keyword' => $frenchData['seo_keyword']
                ]);
        });

        return $this->response->json([
            'code' => 200,
            'data' => $backData
        ]);
    }

    /**
     * @PostMapping(path="deal_img")
     */
    /**
     * @PostMapping(path="deal_img")
     */
    public function images(RequestInterface $request): ResponseInterface
    {
        $products = Db::table('oc_product_image')
            ->orderBy('product_id', 'desc')
            ->get();

        $product_models = [];
        $updated_count = 0;

        if ($products->isNotEmpty()) {
            foreach ($products as $product) {
                $oldImagePath = trim($product->image);

                // 跳过空图
                if (empty($oldImagePath)) {
                    continue;
                }

                // 检查是否包含需要处理的字符（大写字母、空格或非法字符）
                if (preg_match('/[A-Z\s\W]/', $oldImagePath)) {
                    // 分解路径和文件名
                    $pathParts = explode('/', $oldImagePath);
                    $filename = array_pop($pathParts);

                    // 处理文件名
                    $newFilename = $this->normalizeFilename($filename);

                    // 重新组合路径
                    $newImagePath = implode('/', $pathParts) . '/' . $newFilename;

                    // 只有当文件名有变化时才更新
                    if ($newImagePath !== $oldImagePath) {
                        // 更新 image 路径
                        Db::table('oc_product_image')
                            ->where('product_id', $product->product_id)
                            ->update([
                                'image' => $newImagePath,
                            ]);

                        $updated_count++;
                    }
                }

                $product_models[] = $product->model;
            }
        }

        return $this->response->json([
            'code' => 200,
            'message' => "成功更新了 {$updated_count} 条记录的图片路径",
            'data' => $product_models,
        ]);
    }

    /**
     * 规范化文件名
     * 1. 转换为小写
     * 2. 空格替换为中划线
     * 3. 移除非字母数字、连字符和点的字符
     */
    protected function normalizeFilename(string $filename): string
    {
        // 转换为小写
        $filename = strtolower($filename);

        // 替换空格为中划线
        $filename = str_replace(' ', '-', $filename);

        // 移除非字母数字、连字符和点的字符
        $filename = preg_replace('/[^a-z0-9\-\.]/', '', $filename);

        // 处理多个连续的连字符
        $filename = preg_replace('/-+/', '-', $filename);

        return $filename;
    }


    /**
     * @PostMapping(path="insert_rugby")
     */
    public function insertRugby(RequestInterface $request): ResponseInterface
    {
        $products = Db::table('products')
            ->where('status', 1)
            ->whereIn('webname', ['irugbyshop'])
            ->orderBy('product_id', 'desc')
            ->limit(15)
            ->get();

        if ($products->isNotEmpty()) {
            $conn_i = Db::connection('irugbystore');
            $langs = [1, 2];

            foreach ($products as $product) {
                try {
                    // 开始事务
                    Db::beginTransaction();

                    $insertData = json_decode($product->date_added, true);

                    // 确保JSON解码成功
                    if (json_last_error() !== JSON_ERROR_NONE || !is_array($insertData)) {
                        continue;
                    }

                    //查询是否已存在该 model
                    $model = $insertData['model'] ? trim($insertData['model']) : rand(1000,9999);
                    $model = strtolower($model);

                    $exists = $conn_i->select("SELECT product_id FROM oc_product WHERE model = ? LIMIT 1", [$model]);
                    if (!empty($exists)) {
                        continue;
                    }

                    $quantity = $viewed = rand(20, 60);
                    $image = 'catalog/'.$model.'/'.basename($insertData['image'] ?? '');
                    $size_chart = basename($insertData['size_chart'] ?? '');

                    // oc_product
                    $productId = $conn_i->table('oc_product')->insertGetId([
                        'model' => $model,
                        'sku' => '',
                        'upc' => '',
                        'ean' => '',
                        'jan' => '',
                        'isbn' => '',
                        'mpn' => '',
                        'location' => '',
                        'quantity' => $quantity,
                        'stock_status_id' => 7,
                        'image' => $image,
                        'manufacturer_id' => 0,
                        'shipping' => 1,
                        'price' => $insertData['price'] ?? '0.0000',
                        'points' => 0,
                        'tax_class_id' => 2,
                        'date_available' => date('Y-m-d'),
                        'weight' => '0.00000000',
                        'weight_class_id' => 2,
                        'length' => '0.00000000',
                        'width' => '0.00000000',
                        'height' => '0.00000000',
                        'length_class_id' => 1,
                        'subtract' => 0,
                        'minimum' => 1,
                        'sort_order' => 1,
                        'status' => 0,
                        'viewed' => $viewed,
                        'date_added' => date('Y-m-d H:i:s'),
                        'date_modified' => date('Y-m-d H:i:s'),
                        'meta_robots' => '',
                        'seo_canonical' => '',
                        'size_chart' => $size_chart,
                        'notice' => $product->webname.'.com'
                    ]);

                    // oc_product_description
                    foreach ($langs as $val) {
                        $conn_i->table('oc_product_description')->insert([
                            'product_id' => $productId,
                            'language_id' => $val,
                            'name' => $insertData['product_name'] ?? '',
                            'description' => $insertData['description'] ?? '',
                            'tag' => $insertData['tag'] ?? '',
                            'meta_title' => $insertData['meta_title'] ?? '',
                            'meta_description' => $insertData['meta_description'] ?? '',
                            'meta_keyword' => $insertData['meta_keyword'] ?? '',
                            'seo_keyword' => $insertData['meta_keyword'] ?? '',
                            'seo_h1' => $insertData['meta_keyword'] ?? '',
                            'seo_h2' => $insertData['meta_keyword'] ?? '',
                            'seo_h3' => $insertData['meta_keyword'] ?? '',
                            'image_title' => $insertData['product_name'] ?? '',
                            'image_alt' => $insertData['product_name'] ?? ''
                        ]);
                    }

                    //images
                    if(!empty($insertData['images'])){
                        foreach ($insertData['images'] as $key => $val) {
                            $product_image_sort_order = (int)$key+1;
                            $product_image_image = basename($val ?? '');

                            if(!empty($product_image_image)){
                                $product_image_image = 'catalog/'.$model.'/'.$product_image_image;
                                $conn_i->table('oc_product_image')->insert([
                                    'product_id' => $productId,
                                    'image' => $product_image_image,
                                    'sort_order' => $product_image_sort_order
                                ]);
                            }
                        }
                    }

                    //oc_product_option、oc_product_option_value
                    if(!empty($insertData['options'])){
                        $option_value = [
                            'CHOOSE YOUR SIZE' => 11,
                            'PERSONALISE (Optional)' => 14,
                        ];

                        $option_desc_value = ['M' => 47, 'S' => 46, 'Your Name(12 max)' => 49, 'Your Number(2 max)' => 50, 'L' => 48, 'XL' => 51, '2XL' => 52, '3XL' => 53,
                            '4XL' => 54, '5XL' => 55, '3-4 Years' => 56, '5-6 Years' => 57, '7-8 Years' => 58, '9-10 Years' => 59, '11-12 Years' => 60, '13-14 Years' => 61,
                            'YS' => 62, 'YM' => 63, 'YL' => 64, 'YXL' => 65, 'Y2XL' => 66, 'Y3XL' => 67,
                        ];

                        foreach ($insertData['options'] as $val) {
                            $option_id = $option_value[$val['name']] ?? 0;
                            if($option_id > 0){
                                $product_option_id = $conn_i->table('oc_product_option')->insertGetId([
                                    'product_id' => $productId,
                                    'option_id' => $option_id,
                                    'value' => '',
                                    'required' => $val['required']
                                ]);

                                $option_value_price = ($option_id == 14) ? '5.0000' : '0.0000';
                                foreach ($val['values'] as $value) {
                                    $option_value_id = $option_desc_value[$value['name']] ?? 0;

                                    $conn_i->table('oc_product_option_value')->insert([
                                        'product_option_id' => $product_option_id,
                                        'product_id' => $productId,
                                        'option_id' => $option_id,
                                        'option_value_id' => $option_value_id,
                                        'quantity' => $quantity,
                                        'subtract' => 0,
                                        'price' => $option_value_price,
                                        'price_prefix' => '+',
                                        'points' => 0,
                                        'points_prefix' => '+',
                                        'weight' => '0.00000000',
                                        'weight_prefix' => '+'
                                    ]);
                                }
                            }

                        }
                    }

                    //oc_product_special
                    if(isset($insertData['special_price']) && !empty($insertData['special_price'])){
                        $conn_i->table('oc_product_special')->insert([
                            'product_id' => $productId,
                            'customer_group_id' => 1,
                            'priority' => 1,
                            'price' => $insertData['special_price'],
                            'date_start' => '0000-00-00',
                            'date_end' => '0000-00-00'
                        ]);
                    }

                    //oc_product_to_category
                    if(!empty($insertData['categories'])){
                        $categories_arr = ['All Stars' => 2, 'Kangaroos' => 3, 'Manly Warringah Sea Eagles' => 12, 'Melbourne Storm' => 13, 'Newcastle Knights' => 14,
                            'North Queensland Cowboys' => 15, 'Penrith Panthers	' => 16, 'South Sydney Rabbitohs' => 17, 'St George Illawarra Dragons' => 18,
                            'Sydney Roosters' => 19, 'Warriors1' => 20, 'Wests Tigers' => 21, 'Other' => 22, 'State of Origin' => 23, 'NSW Blues' => 24, 'QLD Maroons' => 25,
                            'Wallabies' => 26, 'Aviron Bayonnais' => 28, 'Biarritz Olympique' => 29, 'MHR Rugby' => 30, 'National Rugby Union Team' => 31,
                            'RCT Toulon Rugby' => 33, 'Stade Francais Rugby' => 34, 'Stade Rochelais' => 35, 'Stade Toulousain' => 36, 'Union Bordeaux Begles' => 37,
                            'Argentina' => 39, 'Croatia' => 40, 'FIJI' => 41, 'Georgia' => 42, 'India' => 43, 'Italy' => 44, 'Jamaica' => 45, 'Japan' => 46, 'Lebanon' => 47,
                            'Malaysia' => 48, 'Papua New Guinea ' => 49, 'Portugal' => 50, 'Samoa' => 51, 'Spain' => 52, 'Tonga' => 53, 'USA' => 54, 'Country Gear' => 56,
                            'Leinster' => 57, 'Munster' => 58, 'Ulster' => 59, 'All Blacks' => 61, 'Blackcaps' => 62, 'Blues' => 63, 'Canterbury' => 64, 'Chiefs' => 65,
                            'Crusaders' => 66, 'Highlanders' => 67, 'Hurricanes' => 68, 'Kiwis' => 69, 'Moana Pasifika' => 70, 'Northland' => 71, 'Otago' => 72, 'Others' => 73,
                            'Tasman Mako' => 74, 'Warriors' => 75, 'Cheetahs' => 77, 'Lions' => 78, 'Sharks' => 79, 'Southern Kings' => 80, 'Springboks' => 81, 'Stormers' => 82,
                            'Vodacom Bulls' => 83, 'Barbarians' => 85, 'Bath Rugby' => 86, 'Bristol Bears' => 87, 'British and Irish Lions' => 88, 'Cardiff Blues' => 89,
                            'Edinburgh' => 90, 'England National Rugby Team' => 91, 'Exeter Chiefs' => 92, 'Glasgow Warriors' => 93, 'Great Britain Lions' => 94, 'Harlequins' => 95,
                            'Leeds Rhinos' => 96, 'Newcastle Falcons' => 97, 'Northampton Saints' => 98, 'Ospreys' => 99, 'Sale Sharks' => 100, 'Saracens' => 101,
                            'Scotland National Rugby Team' => 102, 'Super League' => 103, 'Hull FC' => 104, 'Hull Kingston Rovers' => 105, 'St Helens RLFC' => 106,
                            'Wigan Warriors' => 107, 'Wales National Rugby Team' => 108, 'Australia' => 1, 'NRL Telstra Premiership' => 4, 'Parramatta Eels' => 5,
                            'Brisbane Broncos' => 6, 'Canberra Raiders' => 7, 'Canterbury-Bankstown Bulldogs' => 8, 'Cronulla-Sutherland Sharks' => 9, 'Gold Coast Titans' => 11,
                            'Racing 92' => 32, 'World Cup' => 109, 'Ireland' => 55, 'South Africa' => 76, 'United Kingdom' => 84, 'New Zealand' => 60, 'Dolphins' => 10,
                            'France' => 27, 'International' => 38
                        ];
                        foreach ($insertData['categories'] as $val) {
                            $category_id = $categories_arr[$val['name']] ?? 0;
                            if($category_id > 0){
                                $conn_i->table('oc_product_to_category')->insert([
                                    'product_id' => $productId,
                                    'category_id' => $category_id
                                ]);
                            }
                        }
                    }

                    //oc_product_to_layout
                    $conn_i->table('oc_product_to_layout')->insert([
                        'product_id' => $productId,
                        'store_id' => 0,
                        'layout_id' => 0
                    ]);

                    //oc_product_to_store
                    $conn_i->table('oc_product_to_store')->insert([
                        'product_id' => $productId,
                        'store_id' => 0
                    ]);

                    //oc_seo_url
                    $seoUrl = SeoHelper::generateSeoUrl($insertData['product_name']);
                    foreach ($langs as $val) {
                        $conn_i->table('oc_seo_url')->insert([
                            'store_id' => 0,
                            'language_id' => $val,
                            'query' => 'product_id='.$productId,
                            'keyword' => $seoUrl
                        ]);
                    }

                    //products
                    Db::table('products')
                        ->where('id', $product->id)
                        ->update(['status' => 2]);

                    // 提交事务
                    Db::commit();
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollBack();
                    // 记录错误日志
                    $this->logger->error("产品处理失败: ".$e->getMessage()." 产品ID: ".$product->id);
                    continue;
                }
            }
        }

        return $this->response->json([
            'code' => 200,
            'data' => $products,
        ]);
    }

    /**
     * 获取数据
     * @PostMapping(path="rugby")
     */
    public function rugby(RequestInterface $request): ResponseInterface{
        try {
            $getData = $request->all();
            $webname = trim($getData['webname'] ?? '');

            if (empty($webname) || !is_string($webname)) {
                return $this->response->json([
                    'code' => 400,
                    'msg' => '参数 webname 必填，且为字符串'
                ]);
            }

            $stock_status = [
                7 => "In Stock",
                8 => "Pre-Order",
                5 => "Out Of Stock",
                6 => "2-3 Days",
            ];

            $maxProduct = Db::table('products')
                ->where('webname', $webname)
                ->orderBy('product_id', 'desc')
                ->first();
            if (!$maxProduct) {
                $maxProductId = 0;
            }else{
                $maxProductId = $maxProduct->product_id;
            }

            $conn = Db::connection($webname);

            $products = $conn->cursor("SELECT
                    p.product_id,p.model,p.sku,p.upc,p.ean,p.jan,p.isbn,p.mpn,p.location,p.quantity,p.stock_status_id,p.image,p.manufacturer_id,p.shipping,p.price,p.points,p.tax_class_id,p.date_available,p.weight,p.weight_class_id,p.length,p.width,p.height,p.length_class_id,p.subtract,p.minimum,p.sort_order,p.status,
                    pd.name AS product_name, pd.description, pd.tag, pd.meta_title, pd.meta_description, pd.meta_keyword,
                    ps.price as special_price,
                    sc.image_src as size_chart
                FROM oc_product p
                JOIN oc_product_description pd ON p.product_id = pd.product_id
                JOIN oc_product_special ps ON p.product_id = ps.product_id
                JOIN oc_size_chart sc ON p.product_id = sc.product_id
                WHERE p.product_id > ?
                ORDER BY p.product_id ASC
                LIMIT 100", [$maxProductId]);

            if (empty($products)) {
                return $this->response->json([
                    'code' => 200,
                    'data' => [],
                    'msg' => '没有新数据'
                ]);
            }

            $categorys = $conn->cursor("SELECT
                    pta.product_id,
                    pta.category_id,
                    pta.main_category,
                    cd.category_id,
                    cd.name
                FROM oc_product_to_category pta
                JOIN oc_category_description cd ON pta.category_id = cd.category_id");

            // 查询商品属性信息
            $options = $conn->cursor("SELECT
                po.product_id,
                po.product_option_id,
                po.option_id,
                od.name AS option_name,
                po.value AS option_value,
                po.required,
                pov.product_option_value_id,
                pov.option_value_id,
                ovd.name AS option_value_name,
                pov.quantity,
                pov.subtract,
                pov.price,
                pov.price_prefix,
                pov.points,
                pov.points_prefix,
                pov.weight,
                pov.weight_prefix
            FROM oc_product_option po
            LEFT JOIN oc_option_description od ON po.option_id = od.option_id
            LEFT JOIN oc_product_option_value pov ON po.product_option_id = pov.product_option_id
            LEFT JOIN oc_option_value_description ovd ON (pov.option_value_id = ovd.option_value_id AND pov.option_id = ovd.option_id)
            WHERE od.language_id = 1 AND ovd.language_id = 1");

            //图片
            $images = $conn->cursor("SELECT product_image_id,product_id,image
                FROM oc_product_image
                ORDER BY sort_order ASC");

            $products_arr = $categoryMap = $optionMap = $imagesMap = [];

            //分类
            foreach ($categorys as $category) {
                $productId = $category->product_id;
                if (!isset($categoryMap[$productId])) {
                    $categoryMap[$productId] = [];
                }
                $categoryMap[$productId][] = [
                    'category_id' => $category->category_id,
                    'name' => $category->name,
                    'main_category' => $category->main_category,
                ];
            }

            //属性
            foreach ($options as $option) {
                $productId = $option->product_id;
                if (!isset($optionMap[$productId])) {
                    $optionMap[$productId] = [];
                }

                // 组织选项结构
                if (!isset($optionMap[$productId][$option->option_id])) {
                    $optionMap[$productId][$option->option_id] = [
                        'option_id' => $option->option_id,
                        'name' => $option->option_name,
                        'value' => $option->option_value,
                        'required' => $option->required,
                        'values' => []
                    ];
                }

                // 添加选项值
                if ($option->product_option_value_id) {
                    $optionMap[$productId][$option->option_id]['values'][] = [
                        'product_option_value_id' => $option->product_option_value_id,
                        'option_value_id' => $option->option_value_id,
                        'name' => $option->option_value_name,
                        'quantity' => $option->quantity,
                        'subtract' => $option->subtract,
                        'price' => $option->price,
                        'price_prefix' => $option->price_prefix,
                        'points' => $option->points,
                        'points_prefix' => $option->points_prefix,
                        'weight' => $option->weight,
                        'weight_prefix' => $option->weight_prefix
                    ];
                }
            }

            //图片
            foreach ($images as $image) {
                $productId = $image->product_id;
                if (!isset($imagesMap[$productId])) {
                    $imagesMap[$productId] = [];
                }
                $imagesMap[$productId][] = $image->image;
            }

            foreach ($products as $product) {
                $product->stock_status_val = isset($stock_status[$product->stock_status_id]) ? $stock_status[$product->stock_status_id] : 'Unknown';

                $product->categories = $categoryMap[$product->product_id] ?? [];

                $product->images = $imagesMap[$product->product_id] ?? [];

                $productOptions = $optionMap[$product->product_id] ?? [];
                $product->options = array_values($productOptions);

                $products_arr[] = $product;
            }

            // 3. 将新数据写入products表
            $insertData = [];
            foreach ($products_arr as $product) {
                $insertData[] = [
                    'product_id' => $product->product_id,
                    'webname' => $webname,
                    'date_added' => json_encode($product),
                    'status' => 1,
                    'add_time' => date('Y-m-d H:i:s'),
                ];
            }

            if (!empty($insertData)) {
                Db::table('products')->insert($insertData);
            }

            return $this->response->json([
                'code' => 200,
                'data' => $insertData,
            ]);
        } catch (\InvalidArgumentException $e) {
            $this->logger->info("数据库配置错误", $webname);

            return $this->response->json([
                'code' => 500,
                'msg' => '数据库配置错误: ' . $e->getMessage(),
            ]);
        } catch (\PDOException $e) {
            $this->logger->info("数据库连接失败", $webname);

            return $this->response->json([
                'code' => 500,
                'msg' => '数据库连接失败: ' . $e->getMessage(),
            ]);
        } catch (\Throwable $e) {
            $this->logger->info("系统错误", $webname);

            return $this->response->json([
                'code' => 500,
                'msg' => '系统错误: ' . $e->getMessage(),
            ]);
        }
    }

}
